package com.zhy.baselibrary.base

import android.content.Intent
import android.content.res.Configuration
import android.content.res.Resources
import android.os.Build
import android.os.Bundle
import android.os.CountDownTimer
import android.os.Handler
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.blankj.utilcode.util.SPUtils
import com.zhy.baselibrary.expand.showToast
import com.zhy.baselibrary.utils.AppManager
import com.zhy.baselibrary.utils.Klog
import com.zhy.baselibrary.utils.StatusBarUtils
import com.zhy.baselibrary.view.LoadingDialog
import org.greenrobot.eventbus.EventBus
import java.lang.ref.WeakReference
import java.lang.reflect.Method
import java.lang.reflect.ParameterizedType


abstract class BaseActivity<out V : ViewBinding, out VM : BaseViewModel> : AppCompatActivity() {
    var msg = "加载中..."
    var loadProgress = ""
    private var countDownTimer: CountDownTimer? = null
    private val TIMEOUT: Long = 60000 // 60秒
    val binding by lazy {
        val type = javaClass.genericSuperclass as ParameterizedType
        val clazz = type.actualTypeArguments[0] as Class<*>
        val inflate: Method = clazz.getDeclaredMethod("inflate", LayoutInflater::class.java)
        val v = inflate.invoke(null, layoutInflater) as V
        v
    }
    private val loadingDialog: LoadingDialog by lazy { LoadingDialog(this) }
    val model by lazy {
        val type = javaClass.genericSuperclass as ParameterizedType
        val clazz = type.actualTypeArguments[1] as Class<VM>
        ViewModelProvider(this).get(clazz) as VM
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (isFitWindow()) {
            fullScreen()
        }
        setContentView(binding.root)
        registerUIChange()
        AppManager.getAppManager().addActivity(this)
        initCreat(savedInstanceState)
        initialize()
        setListener()
        setData()
    }

    open fun isFitWindow(): Boolean {
        return true
    }

    override fun getResources(): Resources {
        val res = super.getResources()
        val configuration: Configuration = res.configuration
        if (configuration.fontScale !== 1.0f) {
            configuration.fontScale = 1.0f
            res.updateConfiguration(configuration, res.displayMetrics)
        }
        return res
    }


    open fun initCreat(savedInstanceState: Bundle?) {}

    abstract fun initialize()

    open fun setData() {}


    open fun setListener() {}


    fun getText(textView: TextView): String {
        if (textView.text.isEmpty()) {
            return ""
        }
        return textView.text.trim().toString()
    }


    fun checkText(textView: TextView, hint: String): Boolean {
        if (TextUtils.isEmpty(getText(textView))) {
            showToast(hint)
            return true
        }
        return false
    }

    fun checkText(textView: TextView, hint: Int): Boolean {
        if (TextUtils.isEmpty(getText(textView))) {
            showToast(hint)
            return true
        }
        return false
    }

    protected fun launchActivity(clazz: Class<*>) {
        startActivity(Intent(this, clazz))
    }

    protected fun launchActivity(clazz: Class<*>, bundle: Bundle) {
        val intent = Intent(this, clazz)
        intent.putExtras(bundle)
        startActivity(intent)
    }


    open fun <T : BaseViewModel> getViewModel(cls: Class<T>?): T {
        val vm = ViewModelProvider(this)[cls!!]
        return vm
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        dismissLoadingDialog()
        AppManager.getAppManager().finishActivity(this)
    }

    override fun onStop() {
        super.onStop()
        dismissLoadingDialog()
    }

    private fun fullScreen() {
        StatusBarUtils.translucentStatusBar(WeakReference(this))
        StatusBarUtils.setStatusTextColor(initStatusBarTextColor(), this)
    }

    /**
     * 设置状态栏文字色值为深色调
     * @return true 深色调 false 非深色调
     */
    protected open fun initStatusBarTextColor(): Boolean {
        return true
    }

    private fun showLoadingDialog() {
        loadingDialog.setMessage(msg)
        if (!loadingDialog.isShowing) {
            loadingDialog.show()
        }
    }

    private fun dismissLoadingDialog() {
        try {
            if (loadingDialog.isShowing) {
                loadingDialog.dismiss()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun registerUIChange() {
        model.uiModel.showDialog.observe(this) {
            if (it) {
                showLoadingDialog()
            } else {
                Handler().postDelayed({
                    dismissLoadingDialog()
                }, 1000)
            }
        }
        model.uiModel.showProgress.observe(this) {
            if (!it.isNullOrEmpty()) {
                if (loadingDialog.isShowing) {
                    loadingDialog.setProgress(loadProgress)
                }
            }
        }
    }

//    fun resetTimer() {
//        val isPingBao = SPUtils.getInstance().getBoolean("isPingBao")
//        if (!isPingBao) {
//            return
//        }
//        if (countDownTimer != null) {
//            countDownTimer?.cancel()
//        }
//        var pingBaoTime = SPUtils.getInstance().getString("pingBaoTime") ?: "30"
//        if (pingBaoTime.isEmpty()) {
//            pingBaoTime = "30"
//        }
//        countDownTimer = object : CountDownTimer(pingBaoTime.toLong() * 1000, 1000) {
//            override fun onTick(millisUntilFinished: Long) {}
//            override fun onFinish() {
//                countDownTimer?.cancel()
//                countDownTimer = null
//                onTimeout()
//            }
//        }.start()
//    }


    override fun onUserInteraction() {
        super.onUserInteraction()
//        Klog.d("--------onUserInteraction----")
//        resetTimer()
    }

    override fun onPause() {
        super.onPause()
        stopTimer()
    }

    fun stopTimer() {
        if (countDownTimer != null) {
            countDownTimer!!.cancel()
        }
    }

    protected abstract fun onTimeout()
    override fun onResume() {
        super.onResume()
//        resetTimer()
    }

    override fun onStart() {
        super.onStart()
//        val filter = IntentFilter()
//        filter.addAction(Intent.ACTION_SCREEN_ON)
//        filter.addAction(Intent.ACTION_SCREEN_OFF)
//        registerReceiver(screenStateReceiver, filter)
    }

    fun hideBottomUIMenu() {
//隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT <= 11 && Build.VERSION.SDK_INT < 19) { // lower api
            val v = this.window.decorView
            v.systemUiVisibility = View.GONE
        } else if (Build.VERSION.SDK_INT >= 19) {
            val _window = window
            val params = _window.attributes
            params.systemUiVisibility =
                View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE
            _window.attributes = params
        }
    }

    protected fun hideScrollBottomUIMenu() {
//隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT <= 11 && Build.VERSION.SDK_INT < 19) { // lower api
            val v = this.window.decorView
            v.systemUiVisibility = View.GONE
        } else if (Build.VERSION.SDK_INT > 19) {
            val decorView = window.decorView
            val uiOptions = (View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_FULLSCREEN)
            decorView.systemUiVisibility = uiOptions
        }
    }


}

